package m.jclecai.com.adapter.holder;

import android.content.Context;
import android.graphics.Paint;
import android.support.annotation.LayoutRes;
import android.support.v4.content.ContextCompat;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.math.BigDecimal;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import m.jclecai.com.R;
import m.jclecai.com.bean.Matchorder;
import m.jclecai.com.bean.MyLotteryBean;
import m.jclecai.com.bean.RecordsBean;
import m.jclecai.com.bean.RowsBean;
import m.jclecai.com.listener.OnItemClickListener;
import m.jclecai.com.utils.DateUtil;

/**
 * Created by ZD on 2017/5/15.
 */

public class GroupBuyChildHolder extends ViewHolder {

    @BindView(R.id.tv_more)
    TextView tvMore;
    @BindView(R.id.tv_order)
    TextView tvOrder;
    @BindView(R.id.ll_body)
    LinearLayout llBody;
    OnItemClickListener changed;
    String type;//场次类型
    String[] lottery;//当任9场时 投注方案在lottery
    String title = "";
    String orderMoney = "";

    public GroupBuyChildHolder(Context context,  int resource) {
        super(context, resource);
    }

    public void init(List data, int groupPosition, boolean isShowMore,
                     OnItemClickListener changed, String type, String[] lottery,
                     String title, boolean showBuyRecord, String orderMoney) {
        this.orderMoney = orderMoney;
        this.title = title;
        this.lottery = lottery;
        this.type = type;
        this.changed = changed;
        llBody.setVisibility(GONE);
        llBody.removeAllViews();
        tvOrder.setVisibility(GONE);
        tvOrder.setText("\n");
        tvMore.setVisibility(GONE);
        StringBuilder sb = new StringBuilder();
        sb.append("<br/>");
        for (int i = 0; i < data.size(); i++) {
            Object o = data.get(i);
            if (o == null) continue;
            if (groupPosition == 0 && showBuyRecord) {
                if (o instanceof Matchorder) {//如果是Matchorder类型数据 需要表格
                    if (i == 0)
                        addTitle(groupPosition);
                    Matchorder order = (Matchorder) o;
                    addOrderItem(order, i);
                } else if (o instanceof MyLotteryBean) {   //直接文本换行显示
                    MyLotteryBean lt = (MyLotteryBean) o;
                    String txt = lt.getCode()
                            .replaceAll("[|]", "  ")
                            .replaceAll(",", "")
                            .replaceAll("[-]", "+");
                    if (i < data.size() - 1) {
                        sb.append(txt);
                        sb.append("<br/><br/>");
                    } else {
                        sb.append(txt);
                        sb.append("<br/>");
                    }
                    tvOrder.setText(Html.fromHtml(sb.toString()));
                    tvOrder.setVisibility(VISIBLE);
                }
            } else if (groupPosition == 1) {
                if (o instanceof RecordsBean) {
                    if (i == 0)
                        addTitle(groupPosition);
                    //跟单人数
                    RecordsBean record = (RecordsBean) o;
                    addRecordItem(record);
                    tvMore.setVisibility(isShowMore ? VISIBLE : GONE);
                } else if (o instanceof RowsBean) {
                    RowsBean rows = (RowsBean) o;
                    addTermItem(rows, i);
                    tvMore.setVisibility(isShowMore ? VISIBLE : GONE);
                }
            }
        }
    }

    //条目数据的标题
    void addTitle(int groupPosition) {
        View inflate = inflate(getContext(), R.layout.item_bonus_optimiz_view, null);
        TextView tvTitle = (TextView) inflate.findViewById(R.id.tv_title);
        TextView one = (TextView) inflate.findViewById(R.id.tv_one);
        TextView two = (TextView) inflate.findViewById(R.id.tv_two);
        TextView three = (TextView) inflate.findViewById(R.id.tv_three);
        TextView four = (TextView) inflate.findViewById(R.id.tv_four);
        llBody.addView(inflate);
        llBody.setVisibility(VISIBLE);
        if (groupPosition == 0) {
            one.setText("场次");
            two.setText("赛事");
            three.setText("投注");
            four.setText("彩果");
            one.setBackgroundColor(getResources().getColor(R.color.pink_8f9));
            two.setBackgroundColor(getResources().getColor(R.color.pink_8f9));
            three.setBackgroundColor(getResources().getColor(R.color.pink_8f9));
            four.setBackgroundColor(getResources().getColor(R.color.pink_8f9));
//            four.setVisibility(GONE);
            if ("任选9场".equals(type) || "足球胜负".equals(type)) {
                four.setText("比分");
                four.setVisibility(VISIBLE);
            }
        } else {
            one.setText("用户");
            two.setText("认购金额(元)");
            three.setText("认购时间");
            four.setText("奖金分配");
        }
        tvTitle.setVisibility(GONE);
        if (!TextUtils.isEmpty(title)) {
            tvTitle.setText(title);
            tvTitle.setVisibility(VISIBLE);
        }
    }

    /**
     *   是否显示星期view
     * @return
     */
    private float isShowWeek(String[] matchResult){
        float result = 0;
        if (null!=matchResult&&matchResult.length>0){
            String Str = matchResult[0];
            if (!TextUtils.isEmpty(Str)){
                if ("()".equals(Str))
                    return result;
                if (Str.contains("(")&&Str.contains(")")){
                    int index = Str.indexOf("(")+1;
                    int end = Str.indexOf(")");
                    Str = Str.substring(index, end);
                    result = Float.parseFloat(Str);
                    BigDecimal b  =   new  BigDecimal(result);
                    result = b.setScale(2,  BigDecimal.ROUND_HALF_UP).floatValue();
                }
            }
        }
        return  result;
    }

    void addOrderItem(Matchorder order, int index) {
        View inflate = inflate(getContext(), R.layout.item_bonus_optimiz_view, null);
        TextView one = (TextView) inflate.findViewById(R.id.tv_one);
        TextView two = (TextView) inflate.findViewById(R.id.tv_two);
        TextView three = (TextView) inflate.findViewById(R.id.tv_three);
        TextView four = (TextView) inflate.findViewById(R.id.tv_four);
        TextView tv_day = (TextView) inflate.findViewById(R.id.tv_day);
        one.setBackgroundColor(getResources().getColor(R.color.gray_f8));
        two.setBackgroundColor(getResources().getColor(R.color.gray_f8));
        three.setBackgroundColor(getResources().getColor(R.color.gray_f8));
        four.setBackgroundColor(getResources().getColor(R.color.gray_f8));
        StringBuffer o = new StringBuffer();
        if ("任选9场".equals(type) || "足球胜负".equals(type)) {
            if (lottery != null && index < lottery.length)
                three.setText(lottery[index]);
            four.setText(TextUtils.isEmpty(order.getWeekid()) ? "--" : order.getWeekid());
            four.setVisibility(VISIBLE);
        } else {
            if (isShowWeek(order.getMatchResult())==1.0){
                tv_day.setVisibility(VISIBLE);
                tv_day.setText(getWeek(order.getWeek()));
                one.getPaint().setFlags(Paint. STRIKE_THRU_TEXT_FLAG); //中划线
            }else{
                tv_day.setVisibility(GONE);
                o.append(getWeek(order.getWeek()));
            }

            formatSelect(order.getMatchSelect(), order.getMatchResult(), three);
            formatResult(order.getMatchResult(), four);
//            four.setVisibility(GONE);
        }
        o.append("<br><br>" + order.getGame());
        if (!TextUtils.isEmpty(order.getBall()))//以-开头的则绿色否则是红色
            o.append("(<font color=" + (order.getBall().startsWith("-") ? "#008000" : "#ff0000") + ">" + order.getBall() + "</font>)");
        o.append("<br><br>(" + order.getId() + ")");
        one.setText(Html.fromHtml(o.toString()));


        StringBuffer t = new StringBuffer();
        t.append(order.getHome());
        t.append("<br><br>VS<br><br>");
        t.append(order.getVisit());
        if (!TextUtils.isEmpty(order.getScores()))
            t.append("<font color=#ff0000>(" + order.getScores() + ")</font>");

        two.setText(Html.fromHtml(t.toString()));
        llBody.addView(inflate);
        llBody.setVisibility(VISIBLE);
    }

    void formatResult(String[] result, TextView view) {
        view.setText("");
        for (int i = 0; i < result.length; i++) {
            String s = result[i];
            if ("()".equals(s))
                s = "--";
            //红色标记
            view.append(s);
            if (i < result.length - 1) {
                view.append("\n");
            }
            view.setTextColor(ContextCompat.getColor(getContext(), R.color.a));

        }
    }

    //中奖结果标红
    void formatSelect(String[] selects, String[] results, TextView view) {
        /*view.setTextColor(ContextCompat.getColor(getContext(),R.color.a));
        view.setText("");
        for (int i=0;i<select.length;i++){
            String[] mS = select[i].split("[(]");
            if(result.length > 0){
                String[] mR = result[i].split("[(]");
                if(mR[0].equals(mS[0])){
                    //红色标记
                    view.append(result[i]);
                    view.append("\n\n");
                    view.setTextColor(ContextCompat.getColor(getContext(),R.color.font_red));
                }else {
                    view.append(select[i]);
                    view.append("\n\n");
                    view.setTextColor(ContextCompat.getColor(getContext(),R.color.a));
                }
            }else {
                view.append(select[i]);
                view.append("\n\n");
                view.setTextColor(ContextCompat.getColor(getContext(),R.color.a));
            }
        }*/

        String content = "";

        if (selects != null) {

            for (int i = 0; i < selects.length; i++) {

                boolean isAward = false;
                String result = "";

                //开奖结果是有可能为空的；
                if (result != null && i < results.length) {
                    result = results[i];
                    result = result.split("\\(")[0];
                }

                String select = selects[i];
                select = select.split("\\(")[0];

                if (result.equals(select) && !TextUtils.isEmpty(result)) {
                    isAward = true;
                }

                String color = isAward ? "red" : "gray";

                content += createHtml(selects[i], color);

                if (i < selects.length - 1) {
                    content += "<br/>";
                }
            }
            view.setText(Html.fromHtml(content));

        }
    }


    public String createHtml(String content, String color) {
        return "<html><font color='" + color + "'>" + content + "</font></html>";
    }

    String getWeek(String week) {
        if (TextUtils.isEmpty(week)) return "";
        String w = "周一";
        switch (week) {
            case "1":
                w = "周一";
                break;
            case "2":
                w = "周二";
                break;
            case "3":
                w = "周三";
                break;
            case "4":
                w = "周四";
                break;
            case "5":
                w = "周五";
                break;
            case "6":
                w = "周六";
                break;
            case "7":
                w = "周日";
                break;
        }
        return w;
    }

    String format(String[] strs) {
        if (strs == null) return "";
        StringBuilder ret = new StringBuilder();
        for (int i = 0; i < strs.length; i++) {
            ret.append(strs[i]);
            ret.append(" ");
        }
        return ret.toString();
    }

    void addRecordItem(RecordsBean bean) {
        //添加数据
        View inflate = inflate(getContext(), R.layout.item_bonus_optimiz_view, null);
        TextView one = (TextView) inflate.findViewById(R.id.tv_one);
        one.setText(bean.getTeambuy_username());
        TextView two = (TextView) inflate.findViewById(R.id.tv_two);
        two.setText(bean.getTeambuy_onemoney());
        TextView three = (TextView) inflate.findViewById(R.id.tv_three);
        three.setText(
                DateUtil.formatDate(bean.getTeambuy_addtime()
                        , "yyyy-MM-dd HH:mm:ss").replaceAll(" ", "\n"));
        TextView four = (TextView) inflate.findViewById(R.id.tv_four);
        //four.setText("等待开奖");
        four.setText(bean.getTeambuy_winmoney());
        llBody.addView(inflate);
        llBody.setVisibility(VISIBLE);
    }

    void addTermItem(RowsBean rowsBean, final int index) {
        View inflate = inflate(getContext(), R.layout.item_chase_view, null);
        LinearLayout body = (LinearLayout) inflate.findViewById(R.id.item_body);
        body.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (changed != null)
                    changed.onItemClick(index);
            }
        });
        TextView num = (TextView) inflate.findViewById(R.id.tv_num);
        TextView money = (TextView) inflate.findViewById(R.id.tv_money);
        TextView status = (TextView) inflate.findViewById(R.id.tv_status);
        TextView openCode = (TextView) inflate.findViewById(R.id.tv_open_code);
        TextView endTime = (TextView) inflate.findViewById(R.id.tv_end_time);
        TextView alMoney = (TextView) inflate.findViewById(R.id.all_money);
        alMoney.setText(orderMoney + "元");
        num.setText(("第" + rowsBean.getExpect() + "期"));
        status.setText(rowsBean.getIstate() + "\n状态");
        money.setText((rowsBean.getOne_money() + "元"));
        openCode.setText("- -");
        if (!TextUtils.isEmpty(rowsBean.getOpencodes()))
            openCode.setText(rowsBean.getOpencodes());
        endTime.setText(rowsBean.getEndtime());
        llBody.addView(inflate);
        llBody.setVisibility(VISIBLE);
    }

    @OnClick(R.id.tv_more)
    void more() {
        if (this.changed != null)
            this.changed.onItemClick(-1);
    }
}
